﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.Utilities;
using System.Web.Security;

namespace AIS.SharePoint.AspNetFBA.Layouts.AIS.SharePoint.AspNetFBA
{
    public partial class UserEdit : LayoutsPageBase
    {
        private const string _VIEWSTATE_SPID = "_AISSPID";
        private const string _VIEWSTATE_UserName = "_AISUserName";

        /// <summary>
        /// Required rights for the page
        /// </summary>
        protected override SPBasePermissions RightsRequired
        {
            get
            {
                return SPBasePermissions.ManagePermissions | SPBasePermissions.BrowseUserInfo;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                this.CheckRights();

                Code.ConfigSettings Settings = new Code.ConfigSettings(SPContext.Current.Web);
                Code.Claims ClaimHandler = new Code.Claims();

                if (!IsPostBack)
                {
                    string DisplayYes = Code.Common.GetLocalizedResource("$Resources:Display_Yes");
                    string DisplayNo = Code.Common.GetLocalizedResource("$Resources:Display_No");
                    string UserName = this.Request.QueryString["USERNAME"];

                    btnPasswordReset.Visible = Settings.EnableResetPassword && Membership.EnablePasswordReset && !Membership.RequiresQuestionAndAnswer;
                    btnUserEdit.Visible = false;
                    btnUserDelete.Visible = SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.ManagePermissions);

                    // Load the membership data
                    MembershipUser FBAUser = ClaimHandler.MembeshipProvider.GetUser(UserName.Trim(), false);

                    // Load the sharepoint user data
                    SPUser SPUser = null;
                    if (!string.IsNullOrEmpty(UserName))
                    {
                        try
                        {
                            SPClaim UserClaim = ClaimHandler.GetClaimForUserName(UserName);
                            string ClaimBasedUserName = SPClaimProviderManager.Local.EncodeClaim(UserClaim);
                            SPUser = this.Web.AllUsers[ClaimBasedUserName];
                        }
                        catch { }
                    }

                    // Paint the form
                    lblUserName.Text = UserName;
                    lblFullName.Text = (SPUser != null) ? SPUser.Name : "";
                    lblEMail.Text = (FBAUser != null) ? FBAUser.Email : "";
                    lblLastActivityDate.Text = (FBAUser != null) ? FBAUser.LastActivityDate.ToLongDateString() : "";
                    lblLastLoginDate.Text = (FBAUser != null) ? FBAUser.LastLoginDate.ToLongDateString() : "";
                    lblLastPasswordChangeDate.Text = (FBAUser != null) ? FBAUser.LastPasswordChangedDate.ToLongDateString() : "";
                    lblOnline.Text = (FBAUser != null) ? (FBAUser.IsOnline ? DisplayYes : DisplayNo) : "";
                    lblLockedOut.Text = (FBAUser != null) ? (FBAUser.IsLockedOut ? DisplayYes : DisplayNo) : "";

                    btnUnlockUser.Visible = (FBAUser != null) ? FBAUser.IsLockedOut : false;
                    btnViewSharePoint.Visible = (SPUser != null);

                    // Save values in viewstate for future processing
                    ViewState[_VIEWSTATE_SPID] = (SPUser != null) ? SPUser.ID.ToString() : null;
                    ViewState[_VIEWSTATE_UserName] = UserName;
                }
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Processing);
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }

        public void btnViewSharePoint_Click(object sender, EventArgs e)
        {
            Microsoft.SharePoint.Utilities.SPUtility.Redirect("userdisp.aspx?ID=" + ViewState[_VIEWSTATE_SPID].ToString(), Microsoft.SharePoint.Utilities.SPRedirectFlags.RelativeToLayoutsPage, System.Web.HttpContext.Current);
        }

        public void btnClose_Click(object sender, EventArgs e)
        {
            Code.Common.ClosePage("AIS.SharePoint.AspNetFBA/UserList.aspx");
        }

        protected void btnUserEdit_Click(object sender, EventArgs e)
        {
        }

        protected void btnPasswordReset_Click(object sender, EventArgs e)
        {
            try
            {
                Code.ConfigSettings Settings = new Code.ConfigSettings(SPContext.Current.Web);
                Code.Claims ClaimHandler = new Code.Claims();

                if (Membership.EnablePasswordReset && !Membership.RequiresQuestionAndAnswer)
                {
                    string UserName = ViewState[_VIEWSTATE_UserName].ToString();
                    MembershipUser User = ClaimHandler.MembeshipProvider.GetUser(UserName, false);
                    SPUser SPUser = null;
                    try
                    {
                        SPUser = this.Web.AllUsers[SPClaimProviderManager.Local.EncodeClaim(ClaimHandler.GetClaimForUserName(UserName))];
                    }
                    catch { }

                    if (User != null)
                    {
                        string NewPassword = User.ResetPassword();
                        Code.Common.SendEMail(User.Email, Settings.ResetEMailSubject, Settings.ResetEMailBody, User.UserName, (SPUser != null ? SPUser.Name : User.UserName), NewPassword, "");
                        lblOperationResult.Text = Code.Common.GetLocalizedResource("$Resources:Page_UserView_PasswordResetSuccess");
                    }
                }
                else
                {
                    lblOperationResult.Text = Code.Common.GetLocalizedResource("$Resources:Page_UserView_PasswordResetNotAvailable");
                }
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Processing);
                lblOperationResult.Text = Code.Common.GetLocalizedResource("$Resources:Page_UserView_PasswordResetFailed");
            }
            finally
            {
                btnPasswordReset.Visible = false;
            }
        }

        protected void btnUserDelete_Click(object sender, EventArgs e)
        {
            try
            {
                Code.ConfigSettings Settings = new Code.ConfigSettings(SPContext.Current.Web);
                Code.Claims ClaimHandler = new Code.Claims();

                string UserName = ViewState[_VIEWSTATE_UserName].ToString();
                Membership.DeleteUser(UserName);

                try
                {
                    Web.SiteUsers.Remove(SPClaimProviderManager.Local.EncodeClaim(ClaimHandler.GetClaimForUserName(UserName)));
                    Web.Update();
                }
                catch { }
                lblOperationResult.Text = Code.Common.GetLocalizedResource("$Resources:Page_UserView_UserDeleted");
                btnPasswordReset.Visible = false;
                btnUnlockUser.Visible = false;
                btnUserDelete.Visible = false;
                btnUserEdit.Visible = false;
                btnViewSharePoint.Visible = false;

                Code.Common.ClosePage("AIS.SharePoint.AspNetFBA/UserList.aspx");
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Processing);
                lblOperationResult.Text = Code.Common.GetLocalizedResource("$Resources:Page_UserView_DeleteFailed");
            }
        }

        protected void btnUnlockUser_Click(object sender, EventArgs e)
        {
            try
            {
                Code.ConfigSettings Settings = new Code.ConfigSettings(SPContext.Current.Web);
                Code.Claims ClaimHandler = new Code.Claims();

                string UserName = ViewState[_VIEWSTATE_UserName].ToString();
                MembershipUser User = ClaimHandler.MembeshipProvider.GetUser(UserName, false);
                User.UnlockUser();

                btnUnlockUser.Visible = false;
                lblLockedOut.Text = Code.Common.GetLocalizedResource("$Resources:Display_No");
                lblOperationResult.Text = Code.Common.GetLocalizedResource("$Resources:Page_UserView_UserUnlocked");
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Processing);
                lblOperationResult.Text = Code.Common.GetLocalizedResource("$Resources:Page_UserView_UnlockFailed");
            }
        }

    }
}
